//
//  CityListViewController.swift
//  驻外机组
//
//  Created by 苏伟 on 16/3/30.
//  Copyright © 2016年 com.csair. All rights reserved.
//

import UIKit
import SwiftyJSON

private let kTableHeightHeader: CGFloat = 400
private let kTableToBeCutOff: CGFloat = 70
private let dm:DbManager = DbManager()

//城市列表选择
class CityListViewController: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate {
    
    //@IBOutlet weak var imageView: UIImageView!
    
    //@IBOutlet weak var temp: UILabel!
    
    
    @IBOutlet var bigHeaderImageView: UIImageView!
    @IBOutlet var newsTableView: UITableView!
    @IBOutlet var dateLabel: UILabel!
    
    var cityName = "城市列表"
    
    var tableHeaderView: UIView!
    var tableHeaderMaskToBeVisible: CAShapeLayer!
    var newsArray = [News]()
    var arrayCheckCellHasLoaded = [Bool]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        creatingSampleNews()
        stylingDateLabel()
        configureNewsTable()
        updatingTableHeaderView()
        
        //添加一个监听对象
        NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("dealEvent:"), name: "DealDtoinMainThread", object: nil)

        dm.LoadImage("http://10.242.8.38/ofc/file/107.png")
        
        self.arrayCheckCellHasLoaded = [Bool](count: self.newsArray.count, repeatedValue: false)
        
        // 自定义返回按钮
        let backButton = UIBarButtonItem(title: "く返回", style: UIBarButtonItemStyle.Plain, target: self, action: "goBack")
        
        self.navigationController?.navigationItem.leftBarButtonItem = backButton
        self.navigationItem.leftBarButtonItem = backButton
        
        // 弥补因为返回按钮被替换导致的边缘滑入手势失效的问题
        let gesture = UIPanGestureRecognizer(target: self, action: "goBack")
        self.view.addGestureRecognizer(gesture)
        
        //fromAlbum()
    }
    deinit{
        //记得移除通知监听
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    //view移除后调用方法
    override func viewDidAppear(animated: Bool) {
        
    }
    
    //监听完毕回调方法
    func dealEvent(notification:NSNotification) {
        //let userinfo = notification.userInfo as![String:String]
        //var alertmsg = userinfo["value"]! as String
        print("----------回调方法----------")
        //SweetAlert().showAlert("123123")
        
        bigHeaderImageView.image = notification.userInfo!["image"] as! UIImage
    }
    
    
    //获取对应城市的拼音字符串
    func Citypinyin(cityname : String)->String{
        switch cityname {
        case "北京":
            return "beijing"
            
        case "阿姆斯特丹":
            return "amsterdam"
            
        default:
            return "beijing"
        }
    }
    
    
    override func prefersStatusBarHidden() -> Bool {
        return true
    }
    
    func creatingSampleNews() {
        let news1 = News(newsTitle: "", newsCategory: "北京")
        let news2 = News(newsTitle: "", newsCategory: "广州")
        let news3 = News(newsTitle: "", newsCategory: "塔什干")
        let news4 = News(newsTitle: "", newsCategory: "阿姆斯特丹")
        let news5 = News(newsTitle: "", newsCategory: "首尔金浦")
        let news6 = News(newsTitle: "", newsCategory: "首尔仁川")
        let news7 = News(newsTitle: "", newsCategory: "乌鲁木齐")
        let news8 = News(newsTitle: "", newsCategory: "香港")
        
        //newsArray = [news1, news2, news3, news4, news5, news6, news7, news8]
        
        newsArray = [news1,news2,news3,news4,news5,news6,news7,news8]
        
    }
    
    func stylingDateLabel() {
        self.dateLabel.text = cityName
        self.dateLabel.font = UIFont(name: "HelveticaNeue", size: 30)
        self.dateLabel.textColor = UIColor.whiteColor()
    }
    
    //MARK: table
    func configureNewsTable() {
        self.bigHeaderImageView.image = UIImage(named: cityName)
        
        self.tableHeaderView = self.newsTableView.tableHeaderView!
        self.newsTableView.tableHeaderView = nil
        self.newsTableView.addSubview(self.tableHeaderView)
        self.newsTableView.sendSubviewToBack(self.tableHeaderView)
        
        self.newsTableView.contentInset = UIEdgeInsetsMake(kTableHeightHeader, 0, 0, 0)
        self.newsTableView.contentOffset = CGPoint(x: 0, y: -kTableHeightHeader)
        
    }
    
    func updatingTableHeaderView() {
        var newsHeaderTableRect = CGRect(x: 0, y: -kTableHeightHeader, width: self.view.frame.size.width, height: kTableHeightHeader)
        
        if self.newsTableView.contentOffset.y < -kTableHeightHeader {
            newsHeaderTableRect.size.height = -self.newsTableView.contentOffset.y
            newsHeaderTableRect.origin.y = self.newsTableView.contentOffset.y
        }
        self.tableHeaderView.frame = newsHeaderTableRect
        visiblePortionOfNewsTableHeader(newsHeaderTableRect: newsHeaderTableRect)
    }
    
    func visiblePortionOfNewsTableHeader(newsHeaderTableRect newsHeaderTableRect: CGRect) {
        self.tableHeaderMaskToBeVisible = CAShapeLayer()
        self.tableHeaderMaskToBeVisible.fillColor = UIColor.blackColor().CGColor
        self.tableHeaderView.layer.mask = self.tableHeaderMaskToBeVisible
        
        let trapeziumHeaderMask = UIBezierPath()
        trapeziumHeaderMask.moveToPoint(CGPointMake(0, 0))
        trapeziumHeaderMask.addLineToPoint(CGPointMake(newsHeaderTableRect.width, 0))
        trapeziumHeaderMask.addLineToPoint(CGPointMake(newsHeaderTableRect.width, newsHeaderTableRect.height))
        trapeziumHeaderMask.addLineToPoint(CGPointMake(0, newsHeaderTableRect.height - kTableToBeCutOff))
        self.tableHeaderMaskToBeVisible.path = trapeziumHeaderMask.CGPath
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return newsArray.count
    }
    
    
    //cell初始化
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let newsItem = newsArray[indexPath.row]
        
        let cell = tableView.dequeueReusableCellWithIdentifier("NewsCell") as! NewsTableViewCell
        cell.newsCategory.text = newsItem.newsCategory
        cell.newsTitle.text = newsItem.newsTitle
        
        if indexPath.row % 2 == 0 {
            cell.newsCategory.textColor = UIColor.orangeColor()
        } else {
            cell.newsCategory.textColor = UIColor.purpleColor()
        }
        
        return cell
    }
    
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return 40
    }
    
    
    //选中事件
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        let cell = tableView.cellForRowAtIndexPath(indexPath)
        
        var selectIndex = indexPath.row
        var detail = cell?.textLabel?.text
        
//        SweetAlert().showAlert((cell as! NewsTableViewCell).newsCategory.text!, subTitle:(cell as! NewsTableViewCell).newsTitle.text!, style: AlertStyle.None)
        

         let pushedCtrl:TripViewController = self.navigationController?.viewControllers[1] as! TripViewController
        //传值
        pushedCtrl.aa = (cell as! NewsTableViewCell).newsCategory.text as String!
        
        self.navigationController?.popViewControllerAnimated(true)
        
        //self.navigationController?.pushViewController(pushedCtrl, animated: true)
        //self.presentViewController(pushedCtrl, animated: true,completion: nil)
        
//        var tripVC = self.storyboard?.instantiateViewControllerWithIdentifier("TripView") as! TripViewController
//        tripVC.ButtonCityName.titleLabel?.text = (cell as! NewsTableViewCell).newsTitle.text
//        self.navigationController?.pushViewController(tripVC, animated: true)
        
    }
    
    func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        if self.arrayCheckCellHasLoaded[indexPath.row] == false {
            cell.alpha = 0
            
            UIView.animateWithDuration(1, animations: { () -> Void in
                cell.alpha = 1
            });
            self.arrayCheckCellHasLoaded[indexPath.row] = true
        }
    }
    
    //MARK: ScrollView
    //图片下拉伸缩效果
    func scrollViewDidScroll(scrollView: UIScrollView) {
        updatingTableHeaderView()
    }
    
    //返回逻辑
    func goBack(){
        self.navigationController?.popViewControllerAnimated(true)
        Common.rootViewController.mainTabBarController.tabBar.hidden = true
    }

    
    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "showTripView" {
            if let a = segue.destinationViewController as? TripViewController {
                //a.ButtonCityName.setTitle(sender as? String, forState: UIControlState.Normal)
                a.ButtonCityName.setTitle("13", forState: UIControlState.Normal)
            }
        }
    }
    
   
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}
